// 1. setTimeout 实现 setinterval
// 2. 实现精准的setTimeout

// sort 内部实现的是什么算法，时间复杂度 indexof 呢
// 快速排序。希尔排序，堆排，归并排序
// 先序遍历还原二叉树

// https://segmentfault.com/blog/oneweekonedachang

// 抢红包
// useState Hook
// 数字转字符串（非正则写法）

// 1. url 分割 2
function queryParams(queryStr) {
  const res = {};
  // ?name=home&age=20
  const reg = /[?&][^?&]+=[^?&]+/g
  const found = queryStr.match(reg)
  // ['?name=20','&age=20']
  if (!found) return res;
  found.forEach((item) => {
    let temp = item.substring(1).split('=');
    let key = temp[0];
    let val = temp[1];
    res[key] = val;
  })
  return res;
}
console.log(queryParams('?name=13&age=20'))

function queryParams2(queryStr) {
  const res = {};
  const arr = queryStr.split("?")[1].split('&');
  if (!found) return res;
  arr.forEach((item) => {
    let temp = item.split("=")
    let key = temp[0];
    let val = temp[1];
    res[key] = val;
  })
  return res;
}

console.log(queryParams2('?name=13&age=20'))

// 实现react diff 中得到patch 数组的方法，只需要返回插入，删除。更新节点即可
// https://blog.csdn.net/sd19871122/article/details/106837122

function proxy(event, cb, parent, child) {
  parent[event] = function (e) {
    if (parent.contains(child) &&
      e.target === child) {
      cb.call(this)
    }
  }
}

// 实现一个方块的拖拽
var div1 = document.getElementById('div1')
div1.onmousedown = function (event) {
  var chaX = event.clientX - div1.offsetLeft
  var chaY = event.clientY - div1.offsetTop
  document.onmousemove = function (event) {
    div1.style.left = event.clientX - chaX + 'px'
    div1.style.top = event.clientY - chaY + 'px'
  }

  document.onmouseup = function () {
    document.onmousemove = null
  }
}

// 10 转 26 进制转换
function dToBase26(num) {
  let base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  let res = "";
  while (num > 0) {
    // 因为A代表1，所以需要将num减去1再进行模运算
    let index = (num - 1) % 26;
    res = base[index] + res;
    num = Math.floor((num - 1) / 26);
  }
  return res;
}
// 调用函数并输出结果
console.log(dToBase26(1));
console.log(dToBase26(26)); // 输出 z
console.log(dToBase26(27)); // 输出 AA

// 26 转 10
function base26Tod(base26) {
  let base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var res = 0;

  for (let i = 0; i < base26.length; i++) {
    var digit = base.indexOf(base26[i].toUpperCase()) + 1; // 索引+1
    res = res * 26 + digit
  }
  return res
}
// 示例调用
console.log(base26Tod('A'), '0000');
console.log(base26Tod('Z'), '0000'); // 输出 26
console.log(base26Tod('AA'), '0000'); // 输出 27


// 一个非常简化的useState实现
const React = (function () {
  let hooks = [];
  let currentHook = 0;

  return {
    useState(initialValue) {
      hooks[currentHook] = hooks[currentHook] || initialValue;
      const setStateHookIndex = currentHook; // 用于闭包内的setState
      const setState = newValue => (hooks[setStateHookIndex] = newValue);
      return [hooks[currentHook++], setState];
    },
    render(Component) {
      const Comp = Component();
      Comp.render();
      currentHook = 0; // 重置hook索引
    }
  };
})();

// 使用示例
function MyComponent() {
  const [count, setCount] = React.useState(0);

  return {
    click: () => setCount(count + 1),
    render: () => console.log('render:', { count })
  };
}

// 渲染组件
React.render(MyComponent); // render: { count: 0 }
// 模拟用户点击事件
MyComponent().click();
// 重新渲染组件
React.render(MyComponent); // render: { count: 1 }


// react.lazy的实现
function lazy(load) {

  return class extends React.Component {
    state = {
      component: null
    }
    componentDidMount() {
      load().then(component => {
        this.setState({ component: component.default || component })
      })
    }

    render() {
      let { component: TrueComponent } = this.state
      if (TrueComponent) {
        return <TrueComponent {...this.props}></TrueComponent>
      } else {
        return null
      }
    }

  }
}
let LazyHome = lazy(() =>
  import(/* webpackChunkName: "Home" */'./components/Home')
)


function SuspenseHome() {

  return (
    <React.Suspense fallback={<div>loaing</div>}>
      <LazyHome></LazyHome>
    </React.Suspense>
  )
}

// 实现一个 React Schedule 的调度
class Task {
  constructor(priority, callback, dependencies = []) {
    this.priority = priority;
    this.callback = callback;
    this.dependencies = dependencies;
    this.id = Symbol('task_id'); // 使用 Symbol 保证唯一性  
  }
}


class TaskQueue {
  constructor() {
    this.queues = {}; // { priority: [Task, ...] }  
  }

  enqueue(task) {
    const { priority } = task;
    if (!this.queues[priority]) {
      this.queues[priority] = [];
    }
    this.queues[priority].push(task);
  }

  dequeue(priority) {
    const queue = this.queues[priority];
    if (queue && queue.length > 0) {
      return queue.shift();
    }
    return null;
  }

  // 其他方法，如查看队列长度、清空队列等  
}

class Scheduler {
  constructor(taskQueue) {
    this.taskQueue = taskQueue;
  }

  schedule() {
    // 根据优先级选择算法选择任务  
    let highestPriority = null;
    for (let priority in this.taskQueue.queues) {
      if (!highestPriority || Number(priority) > Number(highestPriority)) {
        highestPriority = priority;
      }
    }

    if (highestPriority) {
      const task = this.taskQueue.dequeue(highestPriority);
      if (task) {
        // 执行任务  
        task.callback();
      }
    }
  }
}

const taskQueue = new TaskQueue();
const scheduler = new Scheduler(taskQueue);

// 添加任务到调度器  
const task1 = new Task(1, () => console.log('Task 1'));
const task2 = new Task(2, () => console.log('Task 2'));
const task3 = new Task(3, () => console.log('Task 3'));

taskQueue.enqueue(task1);
taskQueue.enqueue(task2);
taskQueue.enqueue(task3);

// 调度并执行任务  
scheduler.schedule(); // 输出 "Task 3"  
scheduler.schedule(); // 输出 "Task 2"  
scheduler.schedule(); // 输出 "Task 1"